
package com.widget;

import java.util.Timer;
import java.util.TimerTask;

import com.bluesmart.mia.R;
import com.util.DensityUtil;
import com.util.UiUtils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DynamicWave extends View implements SensorEventListener{

	Context mContext;
    // 波纹颜色
    private static final int WAVE_PAINT_COLOR = Color.WHITE;
    // y = Asin(wx+b)+h
    private static float STRETCH_FACTOR_A = 10;
    // 第一条水波移动速度
    private static int TRANSLATE_X_SPEED_ONE = 5;
    // 第二条水波移动速度
//    private static final int TRANSLATE_X_SPEED_TWO = 5;
    private float mCycleFactorW;

    private int mTotalWidth, mTotalHeight;
    private float[] mYPositions;
    private float[] mResetOneYPositions;
//    private float[] mResetTwoYPositions;
    private int mXOffsetSpeedOne;
//    private int mXOffsetSpeedTwo;
    private int mXOneOffset;
//    private int mXTwoOffset;

    private Paint mWavePaint;
    private DrawFilter mDrawFilter;

    public DynamicWave(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        // 将dp转化为px，用于控制不同分辨率上移动速度基本一致
        mXOffsetSpeedOne = UiUtils.dipToPx(context, TRANSLATE_X_SPEED_ONE);
//        mXOffsetSpeedTwo = UiUtils.dipToPx(context, TRANSLATE_X_SPEED_TWO);

        // 初始绘制波纹的画笔
        mWavePaint = new Paint();
        // 去除画笔锯齿
        mWavePaint.setAntiAlias(true);
        mWavePaint.setStrokeWidth(DensityUtil.dip2px(mContext, 1) + 1);
        // 设置风格为实线
        mWavePaint.setStyle(Style.FILL);
        // 设置画笔颜色
        mWavePaint.setColor(Color.parseColor("#FFFFFF"));
        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        
        STRETCH_FACTOR_A = DensityUtil.dip2px(mContext, 5);
        
        initSensor();
    }

//    Timer timer = null;
    int disHeight = 0;
    int yPos = 0;
    View mView;

    public void setYpos(int pos,View view)
    {
    /*	if(timer != null)
    	{
    		timer.cancel();
    		timer = null;
    	}
  	*/
    	if(pos == 0)
    	{
    		yPos = 0;
    		return;
    	}
    	
    	mView = view;
    	disHeight = pos;
    /*	timer = new Timer();
    	timer.schedule(new TimerTask(){
			@Override
			public void run() {
				if(yPos > disHeight)
				{
					yPos -= 1;
				}
				else if(yPos < disHeight)
				{
					yPos += 1;
				}
//				else timer.cancel();
				
				handle.sendEmptyMessage(0);
			}
    	},0,2);*/
    }
    
    Handler handle = new Handler()
    {
    	public void handleMessage(Message msg)
    	{
/*			RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mView.getLayoutParams();
	        params.bottomMargin = yPos + getHeight()/8;
	        if(params.bottomMargin > getHeight() - getHeight()/4)
			{
	        	params.bottomMargin = getHeight() -  getHeight()/3;
				((TextView)mView.findViewById(R.id.value)).setTextColor(Color.parseColor("#4762A8"));
				((TextView)mView.findViewById(R.id.temp)).setTextColor(Color.parseColor("#4762A8"));
			}
			else
			{
				((TextView)mView.findViewById(R.id.value)).setTextColor(Color.WHITE);
				((TextView)mView.findViewById(R.id.temp)).setTextColor(Color.WHITE);
			}
	        
	        mView.setLayoutParams(params);*/
    	}
    };
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        

		if(mAngle < mTotalAngle) mAngle += 0.5;
		else mAngle -= 0.5;
        
        canvas.rotate(mAngle, mTotalWidth/2, mTotalHeight/2);
        /*
        Paint p = new Paint();  
        p.setColor(Color.WHITE);// 设置红色  
        canvas.drawText("画矩形：", 10, 80, p);  
        p.setColor(Color.GRAY);// 设置灰色  
        p.setStyle(Paint.Style.FILL);//设置填满  
        canvas.drawRect(60, 60, 80, 80, p);// 正方形  
        canvas.drawRect(60, 90, 160, 100, p);// 长方形  
        */
        // 从canvas层面去除绘制时锯齿
        canvas.setDrawFilter(mDrawFilter);
//        resetPositonY();
/*        for (int i = 0; i < mTotalWidth; i++) {

            // 减400只是为了控制波纹绘制的y的在屏幕的位置，大家可以改成一个变量，然后动态改变这个变量，从而形成波纹上升下降效果
            // 绘制第一条水波纹
            canvas.drawLine(i, mTotalHeight - mResetOneYPositions[i] - yPos - getHeight()/16, i,
                    mTotalHeight,
                    mWavePaint);
                    mWavePaint);
        }
*/
        // 改变两条波纹的移动点
        mXOneOffset += mXOffsetSpeedOne;
//        mXTwoOffset += mXOffsetSpeedTwo;

        // 如果已经移动到结尾处，则重头记录
        if (mXOneOffset >= mTotalWidth) {
            mXOneOffset = 0;
        }
/*        if (mXTwoOffset > mTotalWidth) {
            mXTwoOffset = 0;
        }*/

        // 引发view重绘，一般可以考虑延迟20-30ms重绘，空出时间片
//        postInvalidate();
        
        int offset = getWidth()/10;
        
        int yPosition = mTotalHeight  - yPos - getHeight()/16;

    	Path path = new Path();  
    	path.moveTo(0, yPosition);//设置Path的起点  
    	
    	int xOffset = 0;
    	int yOffser = yPosition;
    	
        for (int i = 1; i < 10; i++)
        {
        	path.quadTo(xOffset, yOffser, offset*i, yPosition + (i%2)*10); //设置贝塞尔曲线的控制点坐标和终点坐标  
        	xOffset = offset*i;
        	yOffser = yPosition + (i%2)*10;
        }
        canvas.drawPath(path, mWavePaint);
        
        /*
        Path path2=new Path();  
        path2.moveTo(100, 320);//设置Path的起点  
        path2.quadTo(150, 310, 170, 400); //设置贝塞尔曲线的控制点坐标和终点坐标  
        canvas.drawPath(path2, p);//画出贝塞尔曲线  */
    }

    private void resetPositonY() {
        // mXOneOffset代表当前第一条水波纹要移动的距离
        int yOneInterval = mYPositions.length - mXOneOffset;
        // 使用System.arraycopy方式重新填充第一条波纹的数据
        System.arraycopy(mYPositions, mXOneOffset, mResetOneYPositions, 0, yOneInterval);
        System.arraycopy(mYPositions, 0, mResetOneYPositions, yOneInterval, mXOneOffset);
/*
        int yTwoInterval = mYPositions.length - mXTwoOffset;
        System.arraycopy(mYPositions, mXTwoOffset, mResetTwoYPositions, 0,
                yTwoInterval);
        System.arraycopy(mYPositions, 0, mResetTwoYPositions, yTwoInterval, mXTwoOffset);*/
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 记录下view的宽高
        mTotalWidth = w;
        mTotalHeight = h;
        // 用于保存原始波纹的y值
        mYPositions = new float[mTotalWidth];
        // 用于保存波纹一的y值
        mResetOneYPositions = new float[mTotalWidth];
        // 用于保存波纹二的y值
//        mResetTwoYPositions = new float[mTotalWidth];

        // 将周期定为view总宽度
        mCycleFactorW = (float) (2 * Math.PI / mTotalWidth);

        // 根据view总宽度得出所有对应的y值
        for (int i = 0; i < mTotalWidth; i++) {
            mYPositions[i] = (float) (STRETCH_FACTOR_A * Math.sin(mCycleFactorW * i));
        }
    }
    
    float mAngle = 0;
    float mTotalAngle = 0;
    
    private SensorManager sensorManager = null; 
    private Sensor gyroSensor = null; 
    
    void initSensor()
    {
    	sensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); 
    	gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
    	
    	sensorManager.registerListener(this, gyroSensor, SensorManager.SENSOR_DELAY_UI); //为传感器注册监听器 
    }
    
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onSensorChanged(SensorEvent arg0) {
		float angle = arg0.values[SensorManager.DATA_X];
		mTotalAngle = angle*10;
		
		if(mTotalAngle > 50) mTotalAngle = 50;
		else if(mTotalAngle < -50) mTotalAngle = -50;
		

		if(yPos > disHeight)
		{
			yPos -= 1;
		}
		else if(yPos < disHeight)
		{
			yPos += 1;
		}
//		else timer.cancel();
		
		handle.sendEmptyMessage(0);
		this.invalidate();
	}
}
